<?php
namespace app\service;

use think\Db;

class Commission
{
    public static function reward($userid, $touserid, $val, $type = 1)
    {
        $commission = 0;
        $users = db('user')->where(['id'=>['in', [$userid,$touserid]]])->column('*','id');
        $config = db('config_system')->where(['category'=>'invite'])->column('content', 'title');

        if ($type == 1) {
            $add_rate = $config['shouyi_team_'.$users[$touserid]['level']] ?? 0;
            if ($add_rate && $users[$touserid]['level'] > 1) {
                if ($users[$userid]['level'] > 0) {
                    $add_rate -= 0.05;
                }
            }
            $commission = $val * $config['shouyi_1'] + $val * $add_rate;
        }

        return $commission;
    }

    public static function afterBind($userid, $touserid)
    {
        $invite = db('user_invite_record')->where(['user_id'=>$touserid, 'touserid'=>$userid, 'state'=>1])->value('create_time');
        if (!$invite) return '未绑定,请绑定后查询';

        $chongzhi = db('topup')->where(['fk_userid'=>$userid, 'state'=>1, 'addtime'=>['<', date('Y-m-d H:i:s',$invite)]])->sum('money');
        $commission_chongzhi = self::reward($userid, $touserid, $chongzhi);

        $huiyuan = db('order_common')->where(['types'=>6,'user_id'=>$userid, 'status'=>1, 'update_time'=>['<', $invite]])->sum('money');
        $money_rate = db('config_system')->where(['title'=>'money_rate'])->value('content');
        $commission_huiyuan = self::reward($userid, $touserid, $huiyuan*$money_rate);

        return compact('chongzhi', 'commission_chongzhi', 'huiyuan', 'commission_huiyuan');
    }
    /*自动补发充值、充会员收益开始***************/
    /**
     * 获取佣金比例配置
     *
     * @return array 配置数组
     */
    private static function getCommissionRates()
    {
        static $rates = null;
        if ($rates === null) {
            $rates = [
                0 => ['male' => 0.25, 'female' => 0], // 普通会员
                1 => ['male' => 0.30, 'female' => 0], // 超级会员
                2 => ['male' => 0.35, 'female' => 0], // 运营商
                3 => ['male' => 0.40, 'female' => 0], // 合伙人
            ];
        }
        return $rates;
    }

    /**
     * 计算邀请绑定后的佣金收益
     *
     * @param int $invited_id 被邀请者ID（接受邀请的用户）
     * @param int $inviter_id 邀请者ID（发送邀请的用户）
     * @return array 返回包含佣金信息的数组
     */
    public static function afterBind_new($invited_id, $inviter_id)
    {
        // 获取邀请记录
        $inviteRecord = db('user_invite_record')
            ->where(['user_id' => $inviter_id, 'touserid' => $invited_id, 'state' => 1])
            ->order('id desc')
            ->find();

        if (!$inviteRecord) {
            $result = ['error' => '未绑定,请绑定后查询'];

            // 记录错误
            self::logInvite('invite_bind_error', [
                'inviter_id' => $inviter_id,
                'invited_id' => $invited_id,
                'error' => '未找到有效邀请记录'
            ]);

            return $result;
        }

        // 获取邀请人信息和等级
        $inviter = db('user')->find($inviter_id);
        $inviterLevel = $inviter['level'] ?? 0;

        // 获取被邀请人性别
        $invitedUser = db('user')->find($invited_id);
        $gender = $invitedUser['sex'] ?? '';
        $genderKey = '';

        // 根据中文值映射到佣金配置的键
        switch ($gender) {
            case '男':
                $genderKey = 'male';
                break;
            case '女':
                $genderKey = 'female';
                break;
            default:
                $genderKey = 'other'; // 默认使用其他配置
                break;
        }
        // 获取收益比例配置
        $commissionRates = self::getCommissionRates();
        $rate = $commissionRates[$inviterLevel][$genderKey] ?? 0;
        // 确保比例有效
        if ($rate <= 0) {
            self::logInvite('commission_warning', [
                'inviter_id' => $inviter_id,
                'invited_id' => $invited_id,
                'inviter_level' => $inviterLevel,
                'invited_gender' => $gender,
                'message' => '无效的佣金比例配置'
            ]);
            $rate = 0; // 设置为0避免异常
        }

        // 计算绑定时间点前1天的充值记录
        $threeDaysBeforeBind = date('Y-m-d H:i:s', strtotime('-1 days', $inviteRecord['create_time']));
        $bindTime = date('Y-m-d H:i:s', $inviteRecord['create_time']);

        // 计算金币充值收益
        $chongzhi = db('topup')
            ->where('fk_userid', $invited_id)
            ->where('state', 1)
            ->where('addtime', '>=', $threeDaysBeforeBind)
            ->where('addtime', '<=', $bindTime)
            ->where('bdbufa',2)
            ->sum('money');//积分

        $commission_chongzhi = $chongzhi > 0 ? $chongzhi * $rate : 0;

        $rate1=$rate;
        // 计算会员充值收益
        $rate=0.8;//会员直推奖励80%
        $rate2=$rate;
        $huiyuan = db('order_common')
            ->where('types', 6)
            ->where('user_id', $invited_id)
            ->where('status', 1)
            ->where('update_time', '>=', strtotime($threeDaysBeforeBind))
            ->where('update_time', '<=', strtotime($bindTime))
            ->where('bdbufa',2)
            ->sum('money');//人民币

        $commission_huiyuan = $huiyuan > 0 ? $huiyuan * $rate * 10 : 0;

        // 记录计算结果
        self::logInvite('commission_calc', [
            'inviter_id' => $inviter_id,
            'invited_id' => $invited_id,
            'inviter_level' => $inviterLevel,
            'invited_gender' => $gender,
            'ratecz' => $rate1,
            'ratehy' => $rate2,
            'chongzhi_amount' => $chongzhi.'金币',
            'huiyuan_amount' => $huiyuan.'元',
            'commission_chongzhi' => $commission_chongzhi,
            'commission_huiyuan' => $commission_huiyuan,
            'czsql'=>db('topup')->getLastSql(),
            'hysql'=>db('order_common')->getLastSql(),
        ]);
        return [
            // 充值佣金信息
            'commission_chongzhi' => $commission_chongzhi > 0,  // 是否有充值佣金（布尔值）
            'chongzhi' => $commission_chongzhi,                 // 充值佣金金额（数值）

            // 会员佣金信息
            'commission_huiyuan' => $commission_huiyuan > 0,    // 是否有会员佣金（布尔值）
            'huiyuan' => $commission_huiyuan,                   // 会员佣金金额（数值）
        ];
    }

    /**
     * 记录邀请收益相关日志
     *
     * @param string $type 日志类型
     * @param array $data 日志数据
     * @param string $functionType 功能类型
     */
    private static function logInvite($type, $data, $functionType = 'invite')
    {
        $logDate = date('Ymd');
        $logDir = "extend/log/invitebind_bufa/{$logDate}/";

        $logFiles = [
            'invite' => [
                //要求绑定
                'invite_bind' => "invite_bind.log",
                'invite_bind_error' => "invite_bind_error.log",
                //金币充值、会员充值计算
                'commission_calc' => "commission_calc.log",
                'commission_warning' => "commission_warning.log",
                //金币充值、会员充值奖励情况
                'reward_new_ok' => "reward_new_ok.log",
                'reward_new_error' => "reward_new_error.log",
            ],
        ];

        $logFile = $logDir . ($logFiles[$functionType][$type] ?? "invite_{$functionType}_unknown.log");

        if (!is_dir($logDir)) {
            mkdir($logDir, 0755, true);
        }

        $logContent = [
            'timestamp' => date('Y-m-d H:i:s'),
            'function_type' => $functionType,
            'type' => $type,
            'data' => self::serializeData($data)
        ];

        file_put_contents(
            $logFile,
            json_encode($logContent, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . PHP_EOL,
            FILE_APPEND | LOCK_EX
        );
    }

    /**
     * 序列化日志数据
     *
     * @param mixed $data 要序列化的数据
     * @return string 序列化后的字符串
     */
    private static function serializeData($data)
    {
        if (is_array($data) || is_object($data)) {
            return json_encode($data, JSON_UNESCAPED_UNICODE);
        }
        return (string)$data;
    }
    /*自动补发充值、充会员收益结束***************/
}
